using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace App
{
    public partial class Popup : ToolStripDropDown
    {
        Control _content;
        public Control Content
        {
            get { return _content; }
        }

        public Popup(Control content)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }
            _content = content;
            AutoSize = false;
            Items.Add(new ToolStripControlHost(content));
            content.MinimumSize = content.Size;
            content.MaximumSize = content.Size;
            Size = content.Size;
            content.Location = Point.Empty;
            content.Disposed += delegate(object sender, EventArgs e)
            {
                Dispose();
            };
        }

        public void ShowForControl(Control control)
        {
            Rectangle controlRectangle = control.ClientRectangle;
            Point location = control.PointToScreen(new Point(controlRectangle.Left, controlRectangle.Top + controlRectangle.Height));
            Rectangle screen = Screen.FromControl(control).WorkingArea;
            if (location.X + Size.Width > (screen.Left + screen.Width))
            {
                location.X = (screen.Left + screen.Width) - Size.Width;
            }
            if (location.Y + Size.Height > (screen.Top + screen.Height))
            {
                location.Y -= Size.Height + controlRectangle.Height;
            }
            location = control.PointToClient(location);
            Show(control, location, ToolStripDropDownDirection.BelowRight);
        }


        protected override void OnSizeChanged(EventArgs e)
        {
            _content.MinimumSize = Size;
            _content.MaximumSize = Size;
            _content.Size = Size;
            _content.Location = Point.Empty;
            base.OnSizeChanged(e);
        }
    }
}
